package com.xndc.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Druid测试控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/druid")
public class DruidTestController {

    @Autowired
    private DataSource dataSource;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 测试数据源
     */
    @GetMapping("/datasource")
    public Map<String, Object> dataSource() {
        Map<String, Object> result = new HashMap<>();
        result.put("type", dataSource.getClass().getName());
        result.put("success", true);
        
        // 尝试获取连接并记录信息
        try {
            log.info("获取数据库连接成功: {}", dataSource.getConnection());
            result.put("connection", "success");
        } catch (Exception e) {
            log.error("获取数据库连接失败", e);
            result.put("connection", "failed");
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 测试查询
     */
    @GetMapping("/test-query")
    public Map<String, Object> testQuery() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 执行简单查询
            jdbcTemplate.execute("SELECT 1");
            result.put("query", "success");
            
            // 获取数据库版本信息
            List<Map<String, Object>> dbInfo = jdbcTemplate.queryForList("SELECT VERSION() as version");
            if (!dbInfo.isEmpty()) {
                result.put("version", dbInfo.get(0).get("version"));
            }
            
            result.put("success", true);
        } catch (Exception e) {
            log.error("执行查询失败", e);
            result.put("query", "failed");
            result.put("error", e.getMessage());
            result.put("success", false);
        }
        
        return result;
    }
} 